package com.eleadin.ruleengine.token;

import com.eleadin.ruleengine.config.TokenConfig;
import com.github.benmanes.caffeine.cache.Cache;
import com.eleadin.ruleengine.jwt.JwtUtil;
import com.eleadin.ruleengine.jwt.SecurityConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @ClassName CacheTokenHelp
 */
@Slf4j
@Component
public class CacheTokenHelp implements TokenHelper {
    @Autowired
    private TokenConfig tokenConfig;
    @Autowired
    private Cache<String, Object> accessToken;
    @Override
    public TokenModel create(String userId, String userName) {
        String token = JwtUtil.sign(userId, userName, tokenConfig.getSecretKey());
        TokenModel model = new TokenModel(userId, token, userName);
        accessToken.put(userId,token);
        return model;
    }

    @Override
    public boolean check(String token) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        //取出token包含的身份
        String userId = JwtUtil.getClaim(token, SecurityConstant.USER_ID);
        if (StringUtils.isEmpty(userId)) {
            log.error(String.format("认证失败，未解析出userId，token=%s", token));
            return false;
        }
        String authenticatedToken = String.valueOf(accessToken.asMap().get(userId));
        if (!token.equals(authenticatedToken)) {
            log.error(String.format("认证失败，token不匹配，token=%s，userId=%s", token, userId));
            return false;
        }
        accessToken.put(userId,token);
        return true;
    }

    @Override
    public boolean delete(String userId) {
        Object token = accessToken.asMap().remove(userId);
        return true;
    }
}
